<!--
 * @Author: hye0228 1261769443@qq.com
 * @Date: 2022-10-10 14:21:45
 * @LastEditors: ReinerLau lk850593913@gmail.com
 * @LastEditTime: 2022-11-22 09:30:28
 * @FilePath: \v2.0.0\src\components\MyFormDialog.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-dialog
    :model-value="visible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    :title="title"
  >
    <template #default>
      <el-form ref="formRef" :label-width="labelWidth" :model="formData">
        <el-form-item
          v-for="item in options"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :rules="item.rules"
        >
          <template v-if="item.customRender">
            <CustomRender
              v-model="formData[item.prop]"
              :render="item.customRender"
            ></CustomRender>
          </template>
          <template v-else>
            <el-input v-model="formData[item.prop]" clearable></el-input>
          </template>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div class="flex">
        <el-button size="large" class="flex-1" @click="handleClose">
          取消
        </el-button>
        <el-button
          :loading="loading"
          size="large"
          type="primary"
          class="flex-1"
          @click="handleConfirm"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import CustomRender from "./CustomRender.jsx";
import { ref, toRefs, watch } from "vue";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: "",
  },
  options: {
    type: Array,
    default: () => [],
  },
  labelWidth: {
    type: String,
    default: "140px",
  },
  loading: {
    type: Boolean,
    default: false,
  },
  // 正在编辑的信息
  formData: {
    type: Object,
    default: () => ({}),
  },
});
const { visible, formData } = toRefs(props);

const formRef = ref(null);

const emit = defineEmits(["update:visible", "confirm", "update:formData"]);

function handleClose() {
  emit("update:visible", false);
}

function handleConfirm() {
  // 先校验再判断是否关闭
  formRef.value.validate((valid) => {
    if (!valid) return;
    emit("confirm", formData.value);
  });
}

// 每次关闭弹窗，清空表单信息
watch(visible, (newValue) => {
  if (newValue === false) {
    formRef.value.resetFields();
    emit("update:formData", {});
  }
});
</script>
